<template>
  <el-form
    ref="userForm"
    :rules="rules"
    :model="userInfo"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width: 300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input
        v-model="userInfo.password"
        style="width: 300px"
        type="password"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="hSubmit">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getProfileById } from "@/api/user";
import { saveUserDetailById } from "@/api/employees";
export default {
  data() {
    return {
      // 查询参数的接收方式
      userId: this.$route.query.id,
      // 路径参数的接收方式
      //  uesrId: this.$route.params.id,
      // 表单数据
      userInfo: {
        username: "",
        password: "",
      },
      // 校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.loadUserDetailById();
  },
  methods: {
    // 点击按钮
    hSubmit() {
      this.$refs.userForm.validate((valid) => {
        if (!valid) return;
        this.updateUserDetailById()
      });
    },
    // 获取用户信息填充表单
    async loadUserDetailById() {
      try {
        const res = await getProfileById(this.userId);
        console.log("getProfileById", res);
        this.userInfo = { ...res.data, password: "" };
      } catch (err) {
        console.log("getProfileById", err);
      }
    },
    // 更新用户信息
    async updateUserDetailById() {
      try {
        const res = await saveUserDetailById(this.userInfo);
        console.log("getProfileById", res);
        this.$router.back();
      } catch (err) {
        console.log("getProfileById", err);
      }
    },
  },
};
</script>